//
//  CJAppDelegate.m
//  CJModileGMAdapter
//
//  Created by shanghailingye on 04/24/2024.
//  Copyright (c) 2024 shanghailingye. All rights reserved.
//

#import "CJAppDelegate.h"
#import <AVFoundation/AVFoundation.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/ASIdentifierManager.h>
#import "CJEntranceController.h"
#import <CJMobileAd/CJMobileAd.h>
//#import "NSURL+UrlEnocde.h"

@implementation CJAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[[CJEntranceController alloc] init]];
    [self.window makeKeyAndVisible];
    
    [self setupBUAdSDK];
    return YES;
}

- (void)setupBUAdSDK {

#if __has_include(<BUAdTestMeasurement/BUAdTestMeasurement.h>)
    #if DEBUG
        // 测试工具
        [BUAdTestMeasurementConfiguration configuration].debugMode = YES;
    #endif
#endif
    
    BUAdSDKConfiguration *configuration = [BUAdSDKConfiguration configuration];
    configuration.appID = @"5611562";
    configuration.appLogoImage = [UIImage imageNamed:@"AppIcon"];
    configuration.debugLog = @(1);
    configuration.useMediation = true;
    [BUAdSDKManager startWithAsyncCompletionHandler:^(BOOL success, NSError *error) {
        if (success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                BUSplashAd *splashAd = [[BUSplashAd alloc] initWithSlotID:@"103600746" adSize:[UIScreen mainScreen].bounds.size];
                splashAd.supportCardView = YES;
                UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 60)];
                splashAd.mediation.customBottomView = view;
                view.backgroundColor = [UIColor redColor];
            //    splashAd.supportZoomOutView = YES;
                
                // 不支持中途更改代理，中途更改代理会导致接收不到广告相关回调，如若存在中途更改代理场景，需自行处理相关逻辑，确保广告相关回调正常执行。
                splashAd.delegate = self;
                splashAd.tolerateTimeout = 3;
                /***
                广告加载成功的时候，会立即渲染WKWebView。
                如果想预加载的话，建议一次最多预加载三个广告，如果超过3个会很大概率导致WKWebview渲染失败。
                */
                self.splashAd = splashAd;
                [self.splashAd loadAdData];
                
            });
        }
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self requestIDFATracking];
    });
}

- (void)requestIDFATracking {
    if (@available(iOS 14, *)) {
        // iOS14及以上版本需要先请求权限
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
            // 获取到权限后，依然使用老方法获取idfa
            if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
                NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
                    NSLog(@"%@",idfa);
            } else {
                NSLog(@"请在设置-隐私-跟踪中允许App请求跟踪");
            }
        }];
    } else {
        // iOS14以下版本依然使用老方法
        // 判断在设置-隐私里用户是否打开了广告跟踪
        if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
            NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
            NSLog(@"%@",idfa);
        } else {
            NSLog(@"请在设置-隐私-广告中打开广告跟踪功能");
        }
    }
}

#pragma mark ATSplashDelegate
- (void)splashAdLoadSuccess:(BUSplashAd *)splashAd {
    NSLog(@"事件:%s", __FUNCTION__);
}

- (void)splashAdWillShow:(BUSplashAd *)splashAd {
    NSLog(@"事件:%s", __FUNCTION__);
}

// 穿山甲gm不走··，只会走will on show
- (void)splashAdDidShow:(BUSplashAd *)splashAd {
    NSLog(@"事件:%s", __FUNCTION__);
}

- (void)splashAdLoadFail:(nonnull BUSplashAd *)splashAd error:(BUAdError * _Nullable)error {
    NSLog(@"事件:%s", __FUNCTION__);
}

- (void)splashAdRenderSuccess:(nonnull BUSplashAd *)splashAd {
    NSLog(@"事件:%s", __FUNCTION__);
}

- (void)splashAdDidClick:(nonnull BUSplashAd *)splashAd {
    NSLog(@"事件:%s", __FUNCTION__);
}

- (void)splashAdDidClose:(nonnull BUSplashAd *)splashAd closeType:(BUSplashAdCloseType)closeType {
    NSLog(@"事件:%s", __FUNCTION__);
}


- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    NSLog(@"事件---回到前台");
    [self.splashAd showSplashViewInRootViewController:self.window.rootViewController];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
